package com.martini.persistent.service;

import cn.hutool.crypto.digest.BCrypt;
import com.martini.common.domain.LoginInfo;
import com.martini.common.enumeration.LoginStatusEnum;
import com.martini.persistent.entity.SysUser;
import com.martini.persistent.mapper.UserMapper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author martini at 2021/10/11 10:00
 */
@Service
@Component
public class UserService {
    private final UserMapper userMapper;

    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public Integer register(SysUser sysUser) {
        Example example = new Example(SysUser.class);
        example.createCriteria().andEqualTo("username", sysUser.getUsername());
        List<SysUser> sysUsers = userMapper.selectByExample(example);
        if (sysUsers.size() > 0) {
            throw new RuntimeException("重复的用户名");
        }
        String salt = BCrypt.gensalt(10);
        String hashedPassword = BCrypt.hashpw(sysUser.getPassword(), salt);
        sysUser.setPassword(hashedPassword).setSalt(salt);
        return userMapper.insert(sysUser);
    }

    public LoginInfo login(SysUser user) {
        Example example = new Example(SysUser.class);
        example.createCriteria().andEqualTo("username", user.getUsername());
        List<SysUser> sysUsers = userMapper.selectByExample(example);
        if (sysUsers.size() == 0) {
            return new LoginInfo().setStatus(LoginStatusEnum.LOGIN_FAIL).setJwt(null);
        }
        boolean passed = BCrypt.checkpw(user.getPassword(), sysUsers.get(0).getPassword());
        if (!passed) {
            return new LoginInfo().setStatus(LoginStatusEnum.LOGIN_FAIL).setJwt(null);
        }
        return new LoginInfo().setStatus(LoginStatusEnum.LOGIN_OK);
    }
}
